<?php

namespace app\api\controller;

use app\api\service\ShoppingCart as ShoppingCartService;
use app\common\controller\Api;
use think\exception\ValidateException;

/**
 * 购物车接口
 */
class ShoppingCart extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    // protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';
    private $shoppingCartService;

    public function __construct()
    {
        parent::__construct();
        $this->shoppingCartService = new ShoppingCartService;
    }

    /**
     * 查看购物车
     */
    public function list()
    {
        $userId = $this->auth->__get('id');
        $list = $this->shoppingCartService->showShoppingCart($userId);
        return $this->success('返回成功', $list);
    }

    /**
     * 清空购物车
     *
     */
    public function clean()
    {
        $userId = $this->auth->__get('id');
        $this->shoppingCartService->cleanShoppingCart($userId);
        return $this->success();
    }

    /**
     * 添加购物车
     *
     */
    public function add()
    {
        $data = $this->request->post();
        // 参数校验
        $validate  = validate('ShoppingCart');
        if (!$validate->scene('add')->check($data)) {
            // 抛出验证异常
            throw new ValidateException($validate->getError());
        }
        // 添加用户id
        $data['userId'] = $this->auth->__get('id');
        $this->shoppingCartService->addShoppingCart($data);
        return $this->success();
    }

    /**
     * 删除购物车中一个商品
     *
     */
    public function sub()
    {
        $data = $this->request->post();
        // 参数校验
        $validate  = validate('ShoppingCart');
        if (!$validate->scene('sub')->check($data)) {
            // 抛出验证异常
            throw new ValidateException($validate->getError());
        }
        // 添加用户id
        $data['userId'] = $this->auth->__get('id');
        $this->shoppingCartService->subShoppingCart($data);
        return $this->success();
    }
}
